package com.zw.pdm.module.designtask.service;
import com.zw.pdm.entity.basic.DictCommon;
import com.zw.pdm.entity.basic.Org;
import com.zw.pdm.entity.com.DsnProCommon;
import com.zw.pdm.entity.designtask.DsnProStruct;
import com.zw.pdm.entity.production.MakeSheet;
import com.zw.pdm.entity.rep.Sheet;
import com.zw.pdm.module.basic.repository.DictCommonRepository;
import com.zw.pdm.module.designtask.mapper.DesignTaskMapper;
import com.zw.pdm.module.designtask.mapper.ProStructMapper;
import com.zw.pdm.module.designtask.model.ProStructTastModel;
import com.zw.pdm.module.designtask.repository.DsnProCommonRepository;
import com.zw.pdm.module.designtask.repository.DsnProStructRepository;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.CommonUtils;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import static com.zw.pdm.util.BeanUtil.copy;

/**
 * @Description: 产品结构
 * @Author: China.wsg
 * @Date: 2020/10/14 15:15
 */
@Service
@SuppressWarnings("all")
public class ProStructService {

    @Autowired
    private ProStructMapper proStructMapper;
    @Autowired
    private DsnProCommonRepository comProStatusRepository;
    @Autowired
    private DesignTaskMapper designTaskMapper;
    @Autowired
    private DictCommonRepository dictCommonRepository;
    @Autowired
    private DsnProStructRepository dsnProStructRepository;
    @Autowired
    private LogService logService;
    @Autowired
    private DsnProcessService dsnProcessService;

    /**
     * 按条件查询待创建产品结构列表
     *
     * @param proStructTastModel
     * @return
     */
    public List<ProStructTastModel> findProStructTastCreateByQuery(ProStructTastModel proStructTastModel) {
        return proStructMapper.findProStructTastCreateByQuery(proStructTastModel);
    }

    /**
     * 按条件查询产品结构提交/审核状态
     *
     * @param proStructTastModel
     * @return
     */
    public DsnProStruct findProStructStatusByQuery(ProStructTastModel proStructTastModel) {
        proStructTastModel.setCreateCode(ShiroUtils.getUser().getAccount());
        return proStructMapper.findProStructStatusByQuery(proStructTastModel);
    }

    /**
     * 保存产品结构
     *
     * @param dsnProStruct
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer proStructSave(DsnProStruct dsnProStruct) {

        // 取得专业下部分（未删除/已删除）
        List<DsnProStruct> dsnProStructsNoDel = dsnProStructRepository.findByProIdAndSpecialIdAndProPartAndIsDel(dsnProStruct.getProId(),dsnProStruct.getSpecialId(),dsnProStruct.getProPart(),0);
        List<DsnProStruct> dsnProStructsIsDel = dsnProStructRepository.findByProIdAndSpecialIdAndProPartAndIsDel(dsnProStruct.getProId(),dsnProStruct.getSpecialId(),dsnProStruct.getProPart(),1);

        // 判断部分是否已经存在
        if (dsnProStructsNoDel != null && dsnProStructsNoDel.size() > 0) {
            return 10;
        }

        Project project = new Project();
        if (dsnProStructsIsDel != null && dsnProStructsIsDel.size() > 0){
            // 还原被删除部分
            DsnProStruct dsnProStructSave = new DsnProStruct();
            dsnProStructSave = dsnProStructsIsDel.get(0);
            dsnProStructSave.setIsDel(0);
            dsnProStructSave.setCreateCode(ShiroUtils.getUser().getAccount());
            dsnProStructSave.setCreateName(ShiroUtils.getUser().getName());
            dsnProStructSave = dsnProStructRepository.save(dsnProStructSave);
            logService.saveLog("还原产品结构", "项目编号：" + dsnProStructSave.getProCode() + "<br>项目名称：" + dsnProStructSave.getProName() + "<br>结构名称：" + dsnProStruct.getProPart());
        }else {
            // 新增部分
            // 取得项目信息
            project = designTaskMapper.findProjectById(dsnProStruct.getProId());
            // 保存产品结构明细
            DsnProStruct dsnProStructSave = new DsnProStruct();
            dsnProStructSave.setProPart(dsnProStruct.getProPart());
            dsnProStructSave.setProId(dsnProStruct.getProId());
            dsnProStructSave.setProCode(project.getCode());
            dsnProStructSave.setProName(project.getName());
            dsnProStructSave.setSpecialId(dsnProStruct.getSpecialId());
            dsnProStructSave.setSpecial(dictCommonRepository.findById(dsnProStruct.getSpecialId()).get().getName());
            dsnProStructSave.setCreateCode(ShiroUtils.getUser().getAccount());
            dsnProStructSave.setCreateName(ShiroUtils.getUser().getName());
            dsnProStructSave = dsnProStructRepository.save(dsnProStructSave);
            logService.saveLog("添加产品结构", "项目编号：" + project.getCode() + "<br>项目名称：" + project.getName() + "<br>结构名称：" + dsnProStruct.getProPart());
        }
        return 1;
    }

    /**
     * 修改产品结构
     *
     * @param dsnProStruct
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer proStructUpdate(DsnProStruct dsnProStruct) {

        DsnProStruct target = dsnProStructRepository.getOne(dsnProStruct.getId());
        // 判断是否存在提报计划
        if (existRepSheet(target)) {
            return 10;
        }
        // 判断是否存在制作件计划
        if (existMakeSheet(target)) {
            return 20;
        }
        // 取得专业下部分（未删除）
        List<DsnProStruct> dsnProStructsNoDel = dsnProStructRepository.findByProIdAndSpecialIdAndProPartAndIdNotAndIsDel(dsnProStruct.getProId(),dsnProStruct.getSpecialId(),dsnProStruct.getProPart(),dsnProStruct.getId(),0);
        if (dsnProStructsNoDel != null && dsnProStructsNoDel.size() > 0){
            return 30;
        }

        logService.saveLog("修改产品结构", "项目编号：" + target.getProCode() + "<br>项目名称："  + target.getProName() + "<br>" + target.getProPart() + " 修改成 " + dsnProStruct.getProPart());
        dsnProStruct.setSpecial(dictCommonRepository.findById(dsnProStruct.getSpecialId()).get().getName());
        copy(dsnProStruct, target);
        dsnProStructRepository.saveAndFlush(target);
        return 1;
    }

    /**
     * 删除产品结构
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer proStructDel(Integer id) {

        DsnProStruct dsnProStruct = dsnProStructRepository.getOne(id);
        // 判断是否存在提报计划
        if (existRepSheet(dsnProStruct)) {
            return 10;
        }
        // 判断是否存在制作件计划
        if (existMakeSheet(dsnProStruct)) {
            return 20;
        }

        logService.saveLog("删除产品结构", "项目编号：" + dsnProStruct.getProCode() + "<br>项目名称：" + dsnProStruct.getProName() + "<br>结构名称：" + dsnProStruct.getProPart());
        dsnProStruct.setIsDel(1);
        dsnProStructRepository.save(dsnProStruct);
        return 1;
    }

    /**
     * 判断是否存在提报计划
     *
     * @param dsnProStruct
     * @return
     */
    public boolean existRepSheet(DsnProStruct dsnProStruct) {

        List<Sheet> sheets = proStructMapper.findRepSheetByProCodeAndPart(dsnProStruct);
        if (sheets.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否存在制作件计划
     *
     * @param dsnProStruct
     * @return
     */
    public boolean existMakeSheet(DsnProStruct dsnProStruct) {
        List<MakeSheet> sheets = proStructMapper.findMakeSheetByProCodeAndPart(dsnProStruct);
        if (sheets.size() > 0) {
            return true;
        }
        return false;
    }


    /**
     * 查询产品结构
     *
     * @param proId
     * @return
     */
    public List<DsnProStruct> findProStructByQuery(DsnProStruct dsnProStruct) {
        if (CommonUtils.isNull(dsnProStruct.getCreateCode())) {
            dsnProStruct.setCreateCode(ShiroUtils.getUser().getAccount());
        }
        return dsnProStructRepository.findByProIdAndCreateCodeAndIsDelOrderByIdAsc(dsnProStruct.getProId(), dsnProStruct.getCreateCode(), 0);
    }

    /**
     * 提交产品结构待提交
     *
     * @param proId
     * @return
     */
    public int subProStructByProIdAndCreateCode(DsnProStruct dsnProStruct) {

        // 取得项目信息
        Project project = designTaskMapper.findProjectById(dsnProStruct.getProId());
        logService.saveLog("提交产品结构", "项目编号：" + project.getCode() + "<br>项目名称：" + project.getName());

        dsnProStruct.setCreateCode(ShiroUtils.getUser().getAccount());
        return proStructMapper.subProStructByProIdAndCreateCode(dsnProStruct);
    }

    /**
     * 按条件查询待审核产品结构列表
     *
     * @param proStructTastModel
     * @return
     */
    public List<ProStructTastModel> findProStructTastCheckByQuery(ProStructTastModel proStructTastModel) {
        return proStructMapper.findProStructTastCheckByQuery(proStructTastModel);
    }

    /**
     * 查询产品结构（审核页面）
     *
     * @param proId
     * @return
     */
    public List<DsnProStruct> findCheckProStructByQuery(Integer proId) {
        return dsnProStructRepository.findByProIdAndIsDelOrderBySpecialIdAscCreateCodeAscIdAsc(proId, 0);
    }

    /**
     * 驳回产品结构（更新条件项目ID和创建人）
     *
     * @param dsnProStruct
     * @return
     */
    public int rejectProStructByProIdAndCreateCode(DsnProStruct dsnProStruct) {

        logService.saveLog("驳回产品结构", "项目ID：" + dsnProStruct.getProId()
                + "<br>被驳回人：" + dsnProStruct.getCreateCode() + "<br>驳回原因：" + dsnProStruct.getRejectReason());
        return proStructMapper.rejectProStructByProIdAndCreateCode(dsnProStruct);
    }

    /**
     * 审核产品结构
     *
     * @param proId 项目主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean checkProStructByProId(Integer proId) {

        // 判断：有未提交的不允许审核
        int savedCount = proStructMapper.findProStructSavedCount(proId);
        if (savedCount > 0) {
            return false;
        }

        // 更新项目信息
        Project project = designTaskMapper.findProjectById(proId);
        DsnProCommon comProStatus = new DsnProCommon();
        comProStatus.setProId(proId);
        comProStatus.setProCode(project.getCode());
        comProStatus.setStatusTypeId(3);
        comProStatus.setStatusTypeName("产品结构审核状态");
        comProStatus.setStatus(2);
        comProStatusRepository.saveAndFlush(comProStatus);

        // 更新结构明细状态
        DsnProStruct dsnProStruct = new DsnProStruct();
        dsnProStruct.setProId(proId);
        dsnProStruct.setVerifyCode(ShiroUtils.getUser().getAccount());
        dsnProStruct.setVerifyName(ShiroUtils.getUser().getName());
        dsnProStruct.setVerifyTime(new Date());
        proStructMapper.checkProStructByProId(dsnProStruct);
        logService.saveLog("同意产品结构", "项目编号：" + project.getCode() + "<br>项目名称：" + project.getName());
        return true;
    }

    /**
     * 按项目ID查询项目任务信息
     *
     * @param proId
     * @return
     */
    public List<ProStructTastModel> findProTastByQuery(Integer proId) {
        return proStructMapper.findProTastByQuery(proId);
    }

    /**
     * 撤销审核产品结构
     *
     * @param proId 项目主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelProStructByProId(Integer proId) {

        // 删除产品结构审核状态数据
        proStructMapper.delProStructChectStatusByProId(proId);
        // 撤销审核的产品结构
        proStructMapper.cancelProStructByProId(proId);
        Project project = designTaskMapper.findProjectById(proId);
        logService.saveLog("撤销产品结构", "项目编号：" + project.getCode() + "<br>项目名称：" + project.getName());
        return true;
    }

    /**
     * 按分类查询字典数据
     */
    public List<DictCommon> findDictByGroupName(String groupName) {
        return proStructMapper.findDictByGroupName(groupName);
    }

    /**
     * 根据登入人的身份取得对应专业ID
     *
     * @param proStructTastModel
     * @return
     */
    public Integer findOrgInfoByAccount() {
        Org org = proStructMapper.findOrgInfoByAccount(ShiroUtils.getUser().getAccount());
        Integer specTypeId = null;
        if (org != null && org.getName().equals("挤压装备设计所")) {
            specTypeId = 60;
        } else if (org != null && org.getName().equals("熔铸装备设计所")) {
            specTypeId = 60;
        } else if (org != null && org.getName().equals("深加工装备设计所")) {
            specTypeId = 60;
        } else if (org != null && org.getName().equals("流体传动设计所")) {
            specTypeId = 61;
        } else if (org != null && org.getName().equals("自动化与智能控制设计所")) {
            specTypeId = 62;
        }
        return specTypeId;
    }

}
